package mydemo.springcloudalibaba.provide.payment.controller;

import lombok.extern.slf4j.Slf4j;
import mydemo.springcloudalibaba.api.common.entity.CommonResult;
import mydemo.springcloudalibaba.api.common.entity.Payment;
import mydemo.springcloudalibaba.provide.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Value("${server.port}")
    private String serverPost;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment) {
        log.info("payment/create:" + payment.toString());
        int create = paymentService.create(payment);
        if (create > 0) {
            return new CommonResult(200, "成功");
        } else {
            return new CommonResult(500, "处理异常");

        }
    }

    @RequestMapping("/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        return new CommonResult(200, "成功", paymentService.getPaymentById(id));
    }

    @RequestMapping("/discovery")
    public Object discovery() {
        // 取得清單列表
        List<String> list = discoveryClient.getServices();
        for (String obj : list){
            log.info("*****element:" + obj);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t" + instance.getHost() +
                    "\t" + instance.getPort() +"\t" + instance.getUri());
        }
        return  this.discoveryClient;
    }

    @RequestMapping("/payment/lb")
    public String getPaymentLb(){
        return serverPost;
    }

    @RequestMapping("/timeout")
    public CommonResult timeout(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new CommonResult(200, "成功");
    }
}
